package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    @Autowired//注入categoryBrandService
    private CategoryBrandService categoryBrandService;

    @Override
    public PageDTO<BrandDTO> pageQuery(Integer page, Integer rows, String key) {
        //1.构建分页条件
        IPage<Brand> iPage = new Page<>(page,rows);
        //2.抽取条件，判断真假，声明key是否参与条件查询
        Boolean condition = StringUtils.isNotBlank(key);
        //根据name的模糊查询，或者是letter的查询
        //3.分页查询同时包含条件查询
        page(iPage,new QueryWrapper<Brand>()
                .like(condition,"name",key)
                .or()
                .eq(condition,"letter",key));
        //4.根据查询结果，封装分页响应结果，  注意返回的是brandDTO集合，所以要做好转换
        return new PageDTO<>(iPage.getTotal(),iPage.getPages(),BrandDTO.convertEntityList(iPage.getRecords()));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)//回滚策略，所有异常都回滚
    public void addBrand(BrandDTO brandDTO, List<Long> cids) {
        //将brandDTO转换为Brand
        Brand brand = brandDTO.toEntity(Brand.class);
        //保存品牌,调用save方法完成数据的保存，将数据保存在tb_brand表中
        if(this.save(brand)) {
            //将cids通过stream流再调用map获取到每一个cid，CategoryBrand.of（）方法每次都会返回一个CategoryBrand对象
            //接着调用collect中Collectors.toList()返回一个CategoryBrand的集合
            //根据传入的分类集合，以及品牌id，构建中间表对象集合
            saveCategoryBrand(cids, brand.getId());//重构中间表逻辑
        }
    }

    //中间表保存逻辑
    private void saveCategoryBrand(List<Long> cids, Long bid) {
        //将cids通过stream流再调用map获取到每一个cid，CategoryBrand.of（）方法每次都会返回一个CategoryBrand对象
        //接着调用collect中Collectors.toList()返回一个CategoryBrand的集合
        //根据传入的分类集合，以及品牌id，构建中间表对象集合
        List<CategoryBrand> categoryBrands =
                cids
                        .stream()
                        .map(cid -> CategoryBrand.of(cid, bid))
                        .collect(Collectors.toList());
//            List<CategoryBrand> categoryBrands1 = new ArrayList<>();
//            for (Long cid : cids) {
//                CategoryBrand categoryBrand = CategoryBrand.of(cid, brand.getId());
//                categoryBrands1.add(categoryBrand);
//            }
        //saveBatch分批保存执行
        this.categoryBrandService.saveBatch(categoryBrands);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBrand(BrandDTO brandDTO, List<Long> cids) {
        //将brandDTO转换为Brand
        Brand brand = brandDTO.toEntity(Brand.class);
        //如果修该品牌表成功，则去操作中间表
        if(this.updateById(brand)) {
            //因为不知道用户的真实想法，所有直接删除再重新构建
            //对应的SQL语句：delete  from tb_category_brand where brand_id = #{bid}
            this.categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id",brand.getId()));
            //重构中间表逻辑
            saveCategoryBrand(cids, brand.getId());
        }

    }

    @Override
    public List<BrandDTO> listBrandByIds(List<Long> ids) {
        //根据ids分批查询数据库并将其放入List集合中返回
        List<Brand> brands = this.listByIds(ids);
        //调用BrandDTO.convertEntityList方法将brands转换为BrandDTO传输给前端用于展示
        return BrandDTO.convertEntityList(brands);
    }

    @Override
    public List<BrandDTO> queryBrandByCategory(Long cid) {
        //根据分类id去中间表查询中间表对象（就是品牌类）集合，并转换获取中间表对象中所有的品牌id
        List<Long> brandIds = this.categoryBrandService
                .query()
                .eq("category_id", cid)
                .list()
                .stream()
                .map(CategoryBrand::getBrandId)
                .collect(Collectors.toList());
        if(CollectionUtils.isEmpty(brandIds)) {
            throw new LyException(204,"对应品牌为空");
        }
        return this.listBrandByIds(brandIds);
    }

    @Override
    public BrandDTO queryBrandById(Long bid) {
        //直接根据bid查询
        return new BrandDTO(this.getById(bid));
    }
}